﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace Mystery.SharePoint
{
    public static class QuotaExtensions
    {
        private const string DefaultQuotaTemplateKey = "SPM.DefaultQuota";

        /// <summary>
        /// Sets the default quota to use for this site collection
        /// </summary>
        /// <param name="site"></param>
        /// <param name="quotaName">Name of quota</param>
        /// <returns>True if rootweb property bag was updated</returns>
        public static bool SetDefaultQuotaTemplate(this SPSite site, string quotaName)
        {
            return site.RootWeb.SetLocalizableProperty(DefaultQuotaTemplateKey, quotaName);
        }

        /// <summary>
        /// Updates the quota for the site collection
        /// </summary>
        /// <param name="site"></param>
        public static void UpdateQuotaTemplate(this SPSite site)
        {
            if (site == null) throw new ArgumentNullException("site");

            string defaultQuota = site.RootWeb.Properties.Read(DefaultQuotaTemplateKey, "");

            if (site.Quota.QuotaID == 0)
            {
                SPQuotaTemplate qt = SPWebService.ContentService.QuotaTemplates[defaultQuota];
                if (qt != null)
                {
                    Logger.L.AddInformation(Category.Administration,
                        "Setting quota {0} at {1}", qt.Name, site.Url);
                    site.Quota.QuotaID = qt.QuotaID;
                }
            }
        }
    }
}
